# -*- coding: utf-8 -*-

import os
import sys
from contextlib import closing
import re
import jinja2
import hashlib
import simplejson
import time
import werkzeug.utils

import openerp
from openerp import http
from openerp.http import request
from openerp.modules.registry import RegistryManager

from openerp.addons.wechat.enterprise import WxApi, WxApplication, WxTextResponse, WxNewsResponse, WxArticle, WxLink
from openerp.addons.website_mshop.pools import ModelPool, CursorProxy, common_functions, PageProxy, _slug

SUPERUSER_ID = 1

############################################################################################
# 微信企业号"手机商城"应用消息处理类
# 需要配置wechat.enterprise和wechat.application在data/dftg_corp_weixin.xml文件中
#
class WxAppCropMshop(WxApplication):
    is_initialized = False
    wxapi = None

    # def __init__(self):
    #     if self.is_initialized:
    #         return
    #     self.is_initialized = True
    #     # 取得微信应用配置
    #     db_name = request.session.db
    #     db = RegistryManager.get(db_name)
    #     ir_model_data = openerp.registry(db_name)['ir.model.data']
    #     with closing(db.cursor()) as cr:
    #         application_id = ir_model_data.xmlid_to_res_id(cr, 1, 'dftg_weixin.weixin_dftg_assistant_mshop')
    #         if not application_id:
    #             raise Exception('xmlid not found')
    #         wechat_application = openerp.registry(db_name)['wechat.application']
    #         application = wechat_application.browse(cr, SUPERUSER_ID, application_id)
    #         permission_group_ids = application.permission_group_ids
    #         if permission_group_ids:
    #             permission_group = permission_group_ids[0]
    #             self.SECRET = permission_group.secret
    #             self.SECRET_TOKEN = application.callback_token
    #             self.ENCODING_AES_KEY = application.callback_aeskey
    #             self.APP_ID = application.application_id
    #             self.CORP_ID = application.enterprise_id.corp_id.encode("ascii")
    #     self.wxapi = WxApi(self.CORP_ID, self.SECRET)


if hasattr(sys, 'frozen'):
    # When running on compiled windows binary, we don't have access to package loader.
    path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'html'))
    loader = jinja2.FileSystemLoader(path)
else:
    loader = jinja2.PackageLoader('openerp.addons.dftg_weixin', "html")

env = jinja2.Environment('<%', '%>', '${', '}', '%', loader=loader, autoescape=True)


################################################################
# 企业号手机商城页面微信控制器
#
class WeixinAppAssistantController(http.Controller):
    weixin_app = None

    def __init__(self):
        env.globals['_pool'] = ModelPool()
        env.globals['_cr'] = CursorProxy()
        env.globals['_page'] = PageProxy()
        env.globals['_slug'] = _slug
        env.globals.update(common_functions)
        env.filters['tojson'] = simplejson.dumps
        self.weixin_app = WxAppCropMshop()

    #微信回调入口网址
    @http.route('/weixin/app/mshop', auth='public')
    def weixin(self, **kw):
        try:
            result = self.weixin_app.process(request.httprequest.args, request.httprequest.data)
        except AssertionError, e:
            raise Exception(u'估计是应用没有权限组设置，需要在微信配置->微信企业号里的权限组里添加这个应用，配置后需要重启odoo')
        return result
